<template>
  <div class="app-container">
    <header-v></header-v>
    <Goods-v
      :id="item.id"
      :goods="item"
      v-for="item in list"
      :key="item.id"
      :title="item.goods_name"
      :pic="item.goods_img"
      :price="item.goods_price"
      :state="item.goods_state"
      :count="item.goods_count"
      @change-statue="chengeId"
    ></Goods-v>
    <Footer-v
      :amt="amt"
      :fullState="fullState"
      :allCount="allCount"
      @changefalg="changeFalg"
    ></Footer-v>
  </div>
</template>

<script>
//导入axios
import axios from "axios";
import bus from "@/components/eventBus.js";
import header from "@/components/Header/Header.vue";
import Goods from "@/components/Goods/Goods.vue";
import Footer from "@/components/Footer/Footer.vue";
export default {
  data() {
    return {
      list: [],
    };
  },
  methods: {
    // async initCartList() {
    //   const { data: res } = await axios.get("https://www.escook.cn/api/cart");
    //   console.log(res);
    // },
    chengeId(ID) {
      this.list.some((item) => {
        if (item.id == ID.id) {
          item.goods_state = ID.value;
          // 终止循环
          return true;
        }
      });
    },
    addorcut(val) {
      this.list.some((item) => {
        if (item.id == val.id) {
          item.goods_count = val.value;
          return true;
        }
      });
    },
    axiostest() {
      axios
        .get("https://www.escook.cn/api/cart")
        .then((res) => {
          const { data: hehe } = res;
          console.log(hehe);
          if (res.status == 200) {
            this.list = hehe.list;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    changeFalg(e) {
      this.list.forEach((item) => (item.goods_state = e.status));
    },
  },
  created() {
    this.axiostest();
    bus.$on("addCount", (val) => {
      this.addorcut(val);
    });
    bus.$on("cutCount", (val) => {
      this.addorcut(val);
    });
    console.log(bus);
  },
  components: {
    "header-v": header,
    "Goods-v": Goods,
    "Footer-v": Footer,
  },
  // 计算属性
  computed: {
    // 动态计算全选
    fullState() {
      return this.list.every((item) => item.goods_state);
    },
    amt() {
      return this.list
        .filter((item) => item.goods_state)
        .reduce(
          (total, item) => (total += item.goods_price * item.goods_count),
          0
        );
    },
    allCount() {
      return this.list
        .filter((item) => item.goods_state)
        .reduce((total, item) => 
         (total += item.goods_count)
        , 0);
    },
  },
};
</script>

<style lang="less" scoped>
.app-container {
  padding-top: 45px;
  padding-bottom: 50px;
}
</style>
